import express from 'express';
import globalCache from '../cache.js';
import { isExistUser, getPlatform, hasWebLogin, hasLogin, veriPassword, getAccount } from '../middleWare/user/index.js';
import { generateToken } from '../util/common.js';
import { addSql, countSql, detailSql, getResult, listSql, putSql } from '../util/operateSql.js';
import wxLogin from './weixin/loginByWx.js';
import formatTime from '../util/formatTime.js';
import { generateVerify } from '../util/generalCode.js';

var router = express.Router();
/* GET users listing. */

const TABLE1 = 'activity_master.users'
const TABLE2 = 'activity_master.t_orgnization'

/**
 * @params mobile 用户名
 * @params password 密码
 */
router.post('/login', isExistUser, veriPassword, hasWebLogin, function (req, res, next) {
  const { isExistUser, veriPassword, hasWebLogin } = req
  const body = req.body
  const token = generateToken(body.email)
  let tokenValue = { ...body, token }
  
  if (isExistUser && veriPassword && !hasWebLogin) {
    tokenValue = { ...body, token, ...req.userInfo }
    globalCache.setCache('token', token, tokenValue, 1000 * 3600 * 24)
    globalCache.setCache('token', body.email, tokenValue, 1000 * 3600 * 24)

    const sql = putSql(TABLE1, { login_time: formatTime() }, { email: body.email })

    getResult(sql).then(() => {
      res.send(req.app.locals.success({ token,user:req.userInfo }, '登录成功'))
    });

  } else if (isExistUser && !veriPassword) {
    res.send(req.app.locals.error('密码错误'))
  } else if (!isExistUser) {
    res.json(req.app.locals.error('用户不存在'))
  } else if (hasWebLogin) {
    globalCache.setCache('token', token, tokenValue, 1000 * 3600 * 24)
    globalCache.setCache('token', body.email, tokenValue, 1000 * 3600 * 24)
  }

})

/**
 * @params username 用户名
 * @params password 密码
 */
router.post('/logout', hasLogin, function (req, res, next) {
  const hasLogin = req.hasLogin
  globalCache.delCache('token', `${req.headers.authorization}`)
  if (hasLogin) {
    res.send(req.app.locals.success('已存在,登出成功'))
  } else {
    res.send(req.app.locals.error({}, '不存在用户，或者已登出,请清除缓存'))
  }

})

/**
 * @params username 用户名
 * @params password 密码
 */
router.post('/register', isExistUser, async function (req, res, next) {
  const { username, password, email, emailValidCode } = req.body
  const jscode = req.query.jscode
  const existUser = req.isExistUser
  if (existUser) {
    res.send(req.app.locals.error(`${req.sources == 'pc' ? '邮箱' : '手机号'}已被注册`))
    return
  } else if (req.sources === 'applet') {
    // 微信注册
    const info = await wxLogin(jscode)

    req.openid = info.openid

    if (info && info.openid) {
      // 已经注册过
    }
    res.send(req.app.locals.error(info))
  } else if (req.sources === 'pc') {
    if (!emailValidCode) {
      res.json(req.app.locals.error('请输入验证码'))
      return
    }

    const verifyCodeCache = globalCache.getCache('email', email)
    if (verifyCodeCache) {
      const isValidateVerifyCode = verifyCodeCache.value === emailValidCode
      if (!isValidateVerifyCode) {
        res.json(req.app.locals.error('无效的验证码'))
        return
      }
      const sql = addSql(TABLE1, { admin: username, password, email, nickname: '用户'+ generateVerify(10),is_manage: 1 })
			console.log('addSql: ', addSql);
      getResult(sql).then((result) => {
        res.json(req.app.locals.success('注册成功'))
      }).catch((err) => {
        res.json(req.app.locals.error(err.message))
      });
    } else {
      res.json(req.app.locals.error('验证码已过期'))
    }
  }

})

/**
 * 修改人员信息
 */
router.put('/person',getPlatform, (req, res, next) => {
  try {
    let sql = ''
    const data = req.body
    
    if (req.platform == 'pc') {
      const token = req.headers.authorization
      
      const userInfo = globalCache.getCache('token',token)
      
      sql = putSql(TABLE1,data,{email: userInfo.email})
    } else if(req.platform=='applet') {
      const token = req.headers.authorization
      const userInfo = globalCache.getCache('token',token)
      
      const condition = userInfo.is_manage? {email: userInfo.email} : {mobile: userInfo.mobile}
      sql = putSql(TABLE2,data,condition)
    }
    
    getResult(sql).then((result) => {
      if (result) {
        res.send(req.app.locals.success('修改成功'))
      }
    }).catch(err => {
      res.send(req.app.locals.error(err))
    })

  } catch (error) {
    res.json(req.app.locals.error(error))
  }
})


// 人员详情
router.get('/person', getPlatform, async (req, res, next) => {
  const { platform } = req
  if (platform === 'pc') {
    const { authorization } = req.headers

    const { email } = globalCache.getCache('token', authorization)
    const sql = detailSql(TABLE1, { email })

    getResult(sql).then((result) => {

      res.json(req.app.locals.success(result && result[0]))
    }).catch(err => {
      res.json(req.app.locals.error(err))
    })

  } else if (platform == 'applet'){
    const {authorization} = req.headers
    const userInfo = globalCache.getCache('token',authorization)
    const condition = userInfo.is_manage? {email: userInfo.email} : {openid: userInfo.openid}
    const sql = detailSql(TABLE2,condition)
    getResult(sql).then((result) => {
      res.json(req.app.locals.success(result[0]))
    }).catch((err) => {
      res.json(req.app.locals.error(err))
    });

  }
})

/**
 * 通过openid获取个人信息
 */
router.get('/person', (req, res, next) => {
  const token = req.headers.authorization
  const data = globalCache.getCache('token', `${token}`)
  if (data && JSON.stringify(data) !== '{}') {
    try {

      const sql = `select * from ${TABLE1} where openid = '${data.openid}'`

      getResult(sql).then((result) => {
        if (result) {
          res.send(req.app.locals.success(result[0]))
        }
      }).catch(err => {
        res.send(req.app.locals.error(err))
      })

    } catch (error) {

      res.json(req.app.locals.error(error))
    }
    return
  } else {
    res.json(req.app.locals.error('用户未登录'))
  }
})

// 商户列表
router.get('/person/list', getAccount, async (req, res, next) => {
  try {
    const sql = listSql(TABLE1,{...req.query})
    const sql2 = countSql(TABLE1,{...req.query})
    const rows = await getResult(sql)
    const countRows = await getResult(sql2)
    res.json(req.app.locals.success({list: rows,total: countRows[0].count}))
  } catch (error) {
    res.json(req.app.locals.error(error))
  }

})

export { isExistUser };
export default router;
